package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductTempSKUEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.ProductSKUTempMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ProductBeanTempSKU;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ProductTempSKUBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class ProductSKUTempService {
    @Autowired
    private BaseService baseService;
    @Autowired
    private ProductSKUTempMapperImpl productSKUTempMapper;

    public ProductTempSKUEntity SelectById(Long Id) {
        return productSKUTempMapper.selectById(Id);
    }

    public Boolean CheckEntity(Long Id) {
        int rInt = productSKUTempMapper.selectCount(Id);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(ProductTempSKUEntity entity) {
        return productSKUTempMapper.insert(entity);
    }

    public Integer UpdateEntity(ProductTempSKUEntity entity) {
        return productSKUTempMapper.updateByPrimaryKey(entity);
    }

    public List<ProductTempSKUEntity> SelectAll(String tenantId) {
        return productSKUTempMapper.selectAll(tenantId);
    }

    public List<ProductTempSKUEntity> SelectAllByProductIds(Long[] ids, String tenantId) {
        return productSKUTempMapper.selectAllByProductIds(tenantId, ids);
    }

    public Integer DeleteById(Long Id) {
        return productSKUTempMapper.deleteByPrimaryKey(Id);
    }

    public Integer DeleteByIds(Long[] Ids) {
        return productSKUTempMapper.deleteByPrimaryKeys(Ids);
    }

    //新增并更新
    public Integer InsertBatch(List<ProductTempSKUEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = productSKUTempMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }


    /**
     * 订阅物料档案 更新物料档案SKUTemp表数据
     * 未使用
     * @param productApplyRangeId
     * @param detailId
     * @param tenantId
     * @throws IOException
     */
    public void EventProductSKUTempEdit(String productApplyRangeId, String detailId, String tenantId) throws IOException {
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        String requrl = gatewayUrl + ApiYon.getProDetail+"?access_token="+token;
        Map<String, String> params = new HashMap<>();
        if (detailId.equals("") || productApplyRangeId.equals("")) return;
        // 除签名外的其他参数
//        params.put("access_token", token);
        params.put("id", detailId);
        params.put("orgId", productApplyRangeId);//productApplyRangeId
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params) );
        GenericResponse<ProductBeanTempSKU> response = RequestTool.getBean(resString, new TypeReference<GenericResponse<ProductBeanTempSKU>>() {
        });

        List<ProductTempSKUEntity> myDataSKU = new ArrayList<>();
        if (response.getCode().equals("200")) {
            List<ProductTempSKUBean> mySKUList = response.getData().getProductskus();
            if (mySKUList != null && mySKUList.size() > 0) {
                mySKUList.forEach(item -> {
                    ProductTempSKUEntity obj = MyTool.convertBean2Bean(item, ProductTempSKUEntity.class);
                    obj.setSkuName(item.getName());
                    obj.setMyModel(item.getModel());
                    obj.setMyModelDescription(item.getModelDescription());
                    obj.setTenant_id(tenantId);
                    myDataSKU.add(obj);
                });
                int rIntNew = InsertBatch(myDataSKU);
                System.out.println("EventProductSKUTempEdit影响条数" + rIntNew);
            }
        }
    }


    /**
     * 物料SKU档案同步
     *
     * @param tenantId
     * @param idList
     * @return
     * @throws IOException
     */
    public int EventProductSKUEdit(String tenantId, List<String> idList) throws IOException {
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;

        String requrl = gatewayUrl + ApiYon.getProSKU + "?access_token=" + token;
        Map<String, Object> params = new HashMap<>();
        List<String> fields = new ArrayList<>();
        String ids = "code,weight,volume,productId,productCode,id,name,defaultSKU,specNames,modelDescription,model,batchUnit,productName,specIds,specs,salePrice,noTaxCostPrice,erpCode,ustatus," +
                "orgId,productDetailId,productApplyRangeId,shortName,status,batchPrice,fLowestMarkPrice,fNoTaxCostPrice,fMarketPrice,fPrimeCosts,fSettleAccountsRate,barCode,mnemonicCode," +
                "inventoryCount,iOrder,salePoints,saled,iMinOrderQuantity,batchDeliveryDays,erpOuterCode,safetyStock,stockUnit,iDoubleSale,stopStatus";
        fields = Arrays.asList(ids.split(","));
        // 除签名外的其他参数
        params.put("defaultSKU", false);
        params.put("fields", fields);
        if (idList != null && idList.size() > 0) {
            params.put("idList", idList);
        }
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
        GenericResponse<ProductBeanTempSKU> response = RequestTool.getBean(resString, new TypeReference<GenericResponse<ProductBeanTempSKU>>() {
        });

        List<ProductTempSKUEntity> myDataSKU = new ArrayList<>();
        if (response.getCode().equals("200")) {
            List<ProductTempSKUBean> mySKUList = response.getData().getProductskus();
            if (mySKUList != null && mySKUList.size() > 0) {
                mySKUList.forEach(item -> {
                    ProductTempSKUEntity obj = MyTool.convertBean2Bean(item, ProductTempSKUEntity.class);
                    obj.setSkuName(item.getName());
                    obj.setMyModel(item.getModel());
                    obj.setMyModelDescription(item.getModelDescription());
                    obj.setTenant_id(tenantId);
                    myDataSKU.add(obj);
                });
                int rIntNew = InsertBatch(myDataSKU);
                System.out.println("EventProductSKUEdit影响条数" + rIntNew);
                return rIntNew;
            }
        }
        return 0;
    }
}
